package com.example.fileupload.controller;

import com.example.fileupload.exception.StorageFileNotFindException;
import com.example.fileupload.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.stream.Collectors;

@Controller

public class FileUploadController {
    @Autowired
    private StorageService storageService;

    @GetMapping("/")
    public String listUploadedFiles(Model model) {
        model.addAttribute("files",
                storageService.loadAll().map(
                        path -> MvcUriComponentsBuilder
                                .fromMethodName(FileUploadController.class,
                                        "saveFile",
                                        path.getFileName().toString())
                                .build().toUri().toString())
                        .collect(Collectors.toList()));
        return "uploadForm";
    }

    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> saveFile(@PathVariable String filename) {
        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment: filename=\"" + filename + "\"").body(file);
    }

    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        storageService.store(file);
        redirectAttributes.addFlashAttribute("message", "you successfully uploaded " + file.getOriginalFilename() + " !");
        return "redirect:/";
    }

    @ExceptionHandler(StorageFileNotFindException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFindException notFindException) {
        return ResponseEntity.notFound().build();
    }
}
